package com.tbit.uqbike.client.service.impl;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSON;
import com.tbit.common.constant.*;
import com.tbit.common.entity.BalanceChange;
import com.tbit.common.entity.UserAccountMoney;
import com.tbit.uqbike.client.constant.*;
import com.tbit.uqbike.client.constant.enums.PayApiTypeEnum;
import com.tbit.uqbike.client.dao.core.DepositApplyDao;
import com.tbit.uqbike.client.dao.core.RechargePayTypeDao;
import com.tbit.uqbike.client.dao.core.ReturnDepositDao;
import com.tbit.uqbike.client.dao.core.UserAccountMoneyDao;
import com.tbit.uqbike.client.dao.capital.AdaPayLogDao;
import com.tbit.uqbike.client.dao.log.RefundAdapayRecordDao;
import com.tbit.uqbike.client.dao.log.RefundOrderDao;
import com.tbit.uqbike.client.exception.BaseException;
import com.tbit.uqbike.client.pojo.*;
import com.tbit.uqbike.client.pojo.newEntity.*;
import com.tbit.uqbike.client.remote.WeixinPay;
import com.tbit.uqbike.client.remote.adapay.PaymentUtil;
import com.tbit.uqbike.client.remote.zfb.ZFBReturn;
import com.tbit.uqbike.client.service.*;
import com.tbit.uqbike.client.util.DateTimeUtil;
import com.tbit.uqbike.client.util.LogUtil;
import com.tbit.uqbike.client.util.OrderNoUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service("returnDepositService")
public class ReturnDepositServiceImpl implements ReturnDepositService {
    private final static Logger log = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);
    @Autowired
    private ReturnDepositDao returnDepositDao;
    @Autowired
    private UserService userService;
    @Autowired
    private WeixinDepositLogService weixinDepositLogService;
    @Autowired
    private WeixinPayConfigService weixinPayConfigService;
    @Autowired
    private ZfbPayConfigService zfbPayConfigService;
    @Autowired
    private UserAccountLogService userAccountLogService;
    @Autowired
    private RideLogService rideLogService;
    @Autowired
    private PayPalService payPalService;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private AdaPayService adaPayService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private RechargeService rechargeService;
    @Autowired
    private PushMsgLogService pushMsgLogService;

    @Autowired
    private UserAccountMoneyService userAccountMoneyService;
    @Autowired
    private UserAccountMoneyDao userAccountMoneyDao;
    @Autowired
    private AdaPayLogDao adaPayLogDao;
    @Autowired
    private UserAdaPayLogService userAdaPayLogService;
    @Autowired
    private DepositApplyService depositApplyService;
    @Autowired
    private RefundOrderDao refundOrderDao;
    @Autowired
    private WeixinPayService weixinPayService;
    @Autowired
    private RechargePayTypeDao rechargePayTypeDao;
    @Autowired
    private RechargeMerchantService rechargeMerchantService;
    @Autowired
    private RefundAdapayRecordDao refundAdapayRecordDao;

    @Override
    public void insert(ReturnDeposit returnDeposit) {
        returnDepositDao.insert(returnDeposit);
    }

    @Override
    public void apply(Integer accountId, Integer userId, Integer operatorId, String operatorName,
                      String operatorPhone) {
        log.info("押金退款，入参accountId=" + accountId + "userId=" + userId + "operatorId=" + operatorId + "operatorName=" + operatorName + "operatorPhone=" + operatorPhone);
        /**判断是否有未结束订单*/
        RideLog rideLog = rideLogService.getByUserIdNotFinish(userId);
        if (rideLog != null) {
            throw new BaseException("-3018", "押金退还失败，存在未结束骑行");
        }
        User user = userService.getByUserId(userId);

        /**判断个人金额是否为负数*/
        if (user.getMoney() - user.getRideMoney() < 0) {
            throw new BaseException("-3038", "退还押金失败，账户存在欠费金额");
        }

        /**押金冻结、未提交押金、芝麻信用和押金退还中点击退押金提示*/
        if (user.getDepositState() != DepositStateConstant.DEPOSIT_STATE_PAY) {
            throw new BaseException("-3032", "押金状态非法");
        }


        /**调用微信退还押金*/
        List<WeixinDepositLog> weixinDepositLogs = weixinDepositLogService.getNotReturn(userId);
        log.info("待退款押金订单数量=" + weixinDepositLogs.size());
        if (weixinDepositLogs.size() == 0) {
            DepositApply depositApply = new DepositApply(user.getAccountId(),user.getUserId(),user.getPhone(),user.getDepositMoney().intValue(),
                    0,new Date(),RechargeConstant.PLATFORM_TYPE_WEIXIN);
            depositApplyService.add(depositApply);
            throw new BaseException("-3017", "申请成功,预计1-3个工作日原路退回支付账号，请您注意查收");
        }
        String refundNO = OrderNoUtil.getRefundNO();
        String time = DateTimeUtil.getNowTime();
        Integer returnSuccNum = 0;
        for (WeixinDepositLog weixinDepositLog : weixinDepositLogs) {
            Boolean isSucc = false;
            /**判断是微信还是支付宝*/
            if (weixinDepositLog.getType().equals(RechargeConstant.RECHARGE_WEIXIN_APP)
                    || weixinDepositLog
                    .getType().equals(RechargeConstant.RECHARGE_WEIXIN_XCX)) {
                /**获取平台微信支付信息*/
                WeixinPayConfig weixinPayConfig = weixinPayConfigService.getByAccountId(accountId, weixinDepositLog.getType());

                // 老的普通商户充值的订单 ， 引入服务商退款之后的兼容处理
                RechargeMerchant rechargeMerchant = rechargeMerchantService.getByOrderNO(weixinDepositLog.getOut_trade_no());
                if (null != rechargeMerchant) {
                    weixinPayConfig = weixinPayConfigService.getByPartnerAndAppId(rechargeMerchant.getPartner(),weixinPayConfig.getAppId(),false);//商户id，区域id，品牌id
                }

                /**生成微信退款订单号*/
                weixinDepositLog.setOut_refund_no(refundNO);
                /**调用微信退款接口*/
//                isSucc = WeixinPay.return_deposit(weixinPayConfig, weixinDepositLog.getTransaction_id(), weixinDepositLog.getOut_trade_no(), weixinDepositLog.getOut_refund_no(), String.valueOf(weixinDepositLog.getDepositMoney().intValue()));
                String money = String.valueOf(weixinDepositLog.getDepositMoney().intValue());
//                String wxMchPay = cacheService.getBrandRemoteConfigValue(accountId, BrandConstant.WX_MCH_PAY_SWITCH);
                // 根据支付订单号判断订单支付的时候是否使用微信服务商支付
                RechargePayType one = rechargePayTypeDao.getOne(weixinDepositLog.getOut_trade_no());
                boolean isMchPay = false;
                // 非空且为微信服务商支付
                if (Objects.nonNull(one) && one.getType() == 1){
                    isMchPay = true;
                }
                isSucc = WeixinPay.returnMoney(weixinPayConfig, weixinDepositLog.getOut_trade_no(), weixinDepositLog.getOut_refund_no(), money, money, isMchPay);
                if (isSucc){
                    // 退款调用成功进行主动查询退款订单状态
                    String payApiType = isMchPay ? PayApiTypeEnum.WECHAT_MCH_V3.getApiType() : PayApiTypeEnum.WECHAT_V2.getApiType();
                    weixinPayService.sendPayMsg(refundNO, RechargeConstant.PAY_REFUND, payApiType);
                }
            } else if (weixinDepositLog.getType().equals(RechargeConstant.RECHARGE_ZFB_APP)) {
                /**获取平台支付宝支付信息*/ /**支付宝app*/
                ZfbPayConfig zfbPayConfig = zfbPayConfigService.getByAccountId(accountId, RechargeConstant.ZFB_PAY_APP);
                /**生成微信退款订单号*/
                weixinDepositLog.setOut_refund_no(refundNO);
                isSucc = ZFBReturn.returnMoney(zfbPayConfig, weixinDepositLog);
            } else if (weixinDepositLog.getType().equals(RechargeConstant.RECHARGE_ZFB_XCX)) {
                /**获取平台支付宝支付信息*/ /**支付宝小程序*/
                ZfbPayConfig zfbPayConfig = zfbPayConfigService.getByAccountId(accountId, RechargeConstant.ZFB_PAY_XCX);
                /**生成微信退款订单号*/
                weixinDepositLog.setOut_refund_no(refundNO);
                isSucc = ZFBReturn.returnMoney(zfbPayConfig, weixinDepositLog);
            } else if (weixinDepositLog.getType().equals(RechargeConstant.RECHARGE_PAY_PAL)) {
                //paypal退款
                weixinDepositLog.setOut_refund_no(refundNO);
                String resMsg = payPalService.returnDeposit(user, weixinDepositLog);
                LogUtil.info("paymentId:" + weixinDepositLog.getTransaction_id() + ",orderNo:" + weixinDepositLog.getOut_trade_no() + ",押金退还结果：" + resMsg);
                if ("ok".equals(resMsg)) {
                    isSucc = true;
                }
            } else if (weixinDepositLog.getType().equals(RechargeConstant.RECHARGE_PAY_ADAPAY)
                    || weixinDepositLog
                    .getType().equals(RechargeConstant.RECHARGE_PAY_ADAPAY_ZFB)) {
                //System.out.println(weixinDepositLog);
                weixinDepositLog.setOut_refund_no(refundNO);
                AdaPayConfig adaPayConfig = cacheService.getAdaPayConfig(user.getAccountId(),
                        AdaPayConstant.PAY_CHANNEL_WXXCX);
					/*AdaPayLog adaPayLog = adaPayLogService.getByAdaPayId(weixinDepositLog.getOut_trade_no());
					if(adaPayLog==null){
						throw new BaseException("-20015","金额退还失败，请联系客服");
					}
					if(adaPayLog.getState().equals(AdaPayConstant.ADAPAY_LOG_REFUND)||adaPayLog.getState().equals(AdaPayConstant.ADAPAY_LOG_DEFAULT)){
						throw new BaseException("-20015","金额退还失败，请联系客服");
					}*/
                List<UserAdaPayLog> userAdaPayLogs = userAdaPayLogService.getByPaymentId(weixinDepositLog.getOut_trade_no());
                try {
                    if (userAdaPayLogs.isEmpty()) {
                        isSucc = PaymentUtil
                                .createReverse(adaPayConfig, weixinDepositLog.getOut_trade_no(), weixinDepositLog.getDepositMoney(), weixinDepositLog.getOut_refund_no());
                    } else {
                        String pamentId = weixinDepositLog.getOut_trade_no();
                        List<DivMembers> list = new ArrayList<>();
                        for (UserAdaPayLog userAdaPayLog : userAdaPayLogs) {
                            pamentId = userAdaPayLog.getConfirmId();
                            DivMembers divMembers = new DivMembers(userAdaPayLog.getUserNO(), String.format("%.2f", userAdaPayLog.getMoney().doubleValue()
                                    / 100), "N");
                            list.add(divMembers);
                        }
                        String members = JSON.toJSONString(list);
                        Map<String, Object> payment = PaymentUtil.executeRefund(adaPayConfig, pamentId, weixinDepositLog.getDepositMoney(), weixinDepositLog.getOut_refund_no(), members);
                        if (payment.get("status").equals(AdaPayConstant.PAY_STATUS_PENDING) || payment.get("status").equals(
                                AdaPayConstant.PAY_STATUS_SUCCEEDED)) {
                            isSucc = true;
                            /**更改押金充值记录为已退款*/
                            for (UserAdaPayLog userAdaPayLog : userAdaPayLogs) {
                                userAdaPayLog.setRefundMoney(userAdaPayLog.getMoney());
                                userAdaPayLog.setRefundServiceFee(userAdaPayLog.getServiceFee());
                                userAdaPayLog.setRefundFee(userAdaPayLog.getFee());
                                userAdaPayLog.setAllRefundMoney(userAdaPayLog.getRechargeMoney());
                                userAdaPayLog.setRefundTime(new Date());
                                userAdaPayLogService.editRefund(userAdaPayLog);


                                // 记录refundadapayrecord
                                String refundTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                                RefundAdapayRecord refundAdapayRecord = new RefundAdapayRecord(
                                        userAdaPayLog.getBrandId(),userAdaPayLog.getAccountId(),userAdaPayLog.getUserNO(),userAdaPayLog.getPaymentId(),
                                        userId,userAdaPayLog.getOrderNO(),refundNO, weixinDepositLog.getDepositMoney(), userAdaPayLog.getMoney().doubleValue(),
                                        userAdaPayLog.getProportion(),userAdaPayLog.getFee(),userAdaPayLog.getServiceFee(),refundTime,operatorName
                                );
                                refundAdapayRecordDao.insert(refundAdapayRecord);
                            }
                            AdaPayLog adaPayLog = new AdaPayLog();
                            adaPayLog.setRefundMoney(weixinDepositLog.getDepositMoney());
                            adaPayLog.setState(AdaPayConstant.ADAPAY_LOG_REFUND);
                            adaPayLog.setAdaPayId(weixinDepositLog.getOut_trade_no());
                            adaPayLog.setRefundNO(refundNO);
                            adaPayLog.setRefundTime(new Date());
                            adaPayLogDao.editRefund(adaPayLog);
                            adaPayService.addAdaPayRefundLog(userAdaPayLogs, list, refundNO, 0, 0,
                                    0);
                        }
                    }
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
            if (isSucc) {
                log.info("押金退还成功，支付平台订单号=" + weixinDepositLog.getTransaction_id());
                /**修改押金金额*/
                userService.updateDepositMoney(userId, -weixinDepositLog.getDepositMoney());
                returnSuccNum++;
                /**更新押金退还记录*/
                WeixinDepositLog weixinDepositLogUpdate = new WeixinDepositLog();
                weixinDepositLogUpdate.setReturnTime(DateTimeUtil.getNowTime());
                weixinDepositLogUpdate.setTransaction_id(weixinDepositLog.getTransaction_id());
                weixinDepositLogUpdate.setOut_refund_no(weixinDepositLog.getOut_refund_no());
                weixinDepositLogService.updateReturn(weixinDepositLogUpdate);
                /**记录资金变动日志*/
                UserAccountLog userAccountLog = new UserAccountLog();
                userAccountLog.setMoneyType(0);
                userAccountLog.setAccountId(accountId);
                userAccountLog.setMoney(weixinDepositLog.getDepositMoney());
                userAccountLog.setUserId(userId);
                userAccountLog.setOperaTime(DateTimeUtil.getNowTime());
                userAccountLog.setRemark("押金退还");
                userAccountLog.setType(0);
                userAccountLogService.insert(userAccountLog);
                String orderNo = weixinDepositLog.getOut_trade_no();
                if (weixinDepositLog.getType().equals(RechargeConstant.RECHARGE_PAY_ADAPAY)
                        || weixinDepositLog.getType().equals(RechargeConstant.RECHARGE_PAY_ADAPAY_ZFB)) {
                    AdaPayLog adaPayLog = adaPayLogDao.getByAdaPayId(weixinDepositLog.getOut_trade_no());
                    orderNo = adaPayLog.getOrderNO();
                }
                Recharge recharge = rechargeService.getByOrderNO(orderNo);
                log.info("查询区域押金：userId=" + user.getUserId() + "accountId=" + recharge.getAdAccountId());
                UserAccountMoney depositMoney = userAccountMoneyService.getByAccountId(user.getUserId(), BalanceLogChangeTypeContent.capitalType_deposit, recharge.getAdAccountId());
                if (depositMoney != null) {
                    depositMoney.setMoney(-depositMoney.getMoney());
                    depositMoney.setUpdateTime(new Date().getTime());
                    userAccountMoneyDao.edit(depositMoney);
                }
                List<String> merchantNOList = new ArrayList<>();
                merchantNOList.add(recharge.getOrderNO());
                Account account = accountService.getByAccountId(recharge.getAdAccountId());
//                adaPayService.pushRefundDetailLog(user, account, weixinDepositLog.getDepositMoney(), refundNO, refundNO,
//                        recharge, operatorId, operatorName, operatorPhone, BusinessConstant.BUSINESS_USER_REFUND_DEPOSIT, null, null);
//                adaPayService.pushRefundLog(user, account, weixinDepositLog.getDepositMoney(), refundNO, merchantNOList, recharge, RefundLogContent.deposit_Refund,
//                        null, operatorId, operatorName, operatorPhone, null);
                adaPayService.pushRefundDetailLog(user, account, weixinDepositLog.getDepositMoney(), refundNO, refundNO,
                        recharge, operatorId, operatorName, operatorPhone, BusinessConstant.BUSINESS_USER_REFUND_DEPOSIT, null, null,new DateTime(time));
                adaPayService.pushRefundLog(user, account, weixinDepositLog.getDepositMoney(), refundNO, merchantNOList, recharge, RefundLogContent.deposit_Refund,
                        null, operatorId, operatorName, operatorPhone, null,new DateTime(time));
                BalanceChange balanceChange = new BalanceChange(user.getUserId(), user.getPhone(), user.getName()
                        , account.getAccountId(), user.getAccountId(), weixinDepositLog.getDepositMoney().longValue(), weixinDepositLog.getDepositMoney().longValue()
                        , 0L, IncomeTypeContent.inComeRefund,
                        BalanceLogChangeTypeContent.capitalType_deposit, BalanceLogCapitalTypeContent.USER_REFUNDS_DEPOSIT
                        , new Date().getTime(), "退押金", refundNO);
                pushMsgLogService.sendPushLog(JSON.toJSONString(balanceChange), TableNameConstant.BALANCECHANGE);

            } else {
                log.warn("押金退还失败，支付平台订单号=" + weixinDepositLog.getTransaction_id());
            }
        }

        /**如果全部成功，更改押金状态*/
        if (returnSuccNum == weixinDepositLogs.size()) {
            userService.updateDeposit(userId, 0);
        } else {
            DepositApply depositApply = new DepositApply(user.getAccountId(),user.getUserId(),user.getPhone(),user.getDepositMoney().intValue(),
                    0,new Date(),RechargeConstant.PLATFORM_TYPE_WEIXIN);
            depositApplyService.add(depositApply);
            throw new BaseException("-3017", "申请成功,预计1-3个工作日原路退回支付账号，请您注意查收");
        }
    }

    /** 押金异步 */
//    @Override
    public void applyNew(Integer accountId, Integer userId, Integer operatorId, String operatorName,
                      String operatorPhone) {
        log.info("押金退款，入参accountId=" + accountId + "userId=" + userId + "operatorId=" + operatorId + "operatorName=" + operatorName + "operatorPhone=" + operatorPhone);
        /**判断是否有未结束订单*/
        RideLog rideLog = rideLogService.getByUserIdNotFinish(userId);
        if (rideLog != null) {
            throw new BaseException("-3018", "押金退还失败，存在未结束骑行");
        }
        User user = userService.getByUserId(userId);

        /**判断个人金额是否为负数*/
        if (user.getMoney() - user.getRideMoney() < 0) {
            throw new BaseException("-3038", "退还押金失败，账户存在欠费金额");
        }

        /**押金冻结、未提交押金、芝麻信用和押金退还中点击退押金提示*/
        if (user.getDepositState() != DepositStateConstant.DEPOSIT_STATE_PAY) {
            throw new BaseException("-3032", "押金状态非法");
        }


        /**调用微信退还押金*/
        List<WeixinDepositLog> weixinDepositLogs = weixinDepositLogService.getNotReturn(userId);
        log.info("待退款押金订单数量=" + weixinDepositLogs.size());
        if (weixinDepositLogs.size() == 0) {
            DepositApply depositApply = new DepositApply(user.getAccountId(),user.getUserId(),user.getPhone(),user.getDepositMoney().intValue(),
                    0,new Date(),RechargeConstant.PLATFORM_TYPE_WEIXIN);
            depositApplyService.add(depositApply);
            throw new BaseException("-3017", "申请成功,预计1-3个工作日原路退回支付账号，请您注意查收");
        }
        String refundNO = OrderNoUtil.getRefundNO();
        String time = DateTimeUtil.getNowTime();
        Integer returnSuccNum = 0;
        for (WeixinDepositLog weixinDepositLog : weixinDepositLogs) {
            Boolean isAdaPay = false;
            Boolean isSucc = false;
            /**判断是微信还是支付宝*/
            if (weixinDepositLog.getType().equals(RechargeConstant.RECHARGE_WEIXIN_APP)
                    || weixinDepositLog
                    .getType().equals(RechargeConstant.RECHARGE_WEIXIN_XCX)) {
                log.info("微信app/小程序退押金");
                /**获取平台微信支付信息*/
                WeixinPayConfig weixinPayConfig = weixinPayConfigService.getByAccountId(accountId, weixinDepositLog.getType());

                // 老的普通商户充值的订单 ， 引入服务商退款之后的兼容处理
                RechargeMerchant rechargeMerchant = rechargeMerchantService.getByOrderNO(weixinDepositLog.getOut_trade_no());
                if (null != rechargeMerchant) {
                    weixinPayConfig = weixinPayConfigService.getByPartnerAndAppId(rechargeMerchant.getPartner(),weixinPayConfig.getAppId(),false);//商户id，区域id，品牌id
                }

                /**生成微信退款订单号*/
                weixinDepositLog.setOut_refund_no(refundNO);
                /**调用微信退款接口*/
//                isSucc = WeixinPay.return_deposit(weixinPayConfig, weixinDepositLog.getTransaction_id(), weixinDepositLog.getOut_trade_no(), weixinDepositLog.getOut_refund_no(), String.valueOf(weixinDepositLog.getDepositMoney().intValue()));

                String money = String.valueOf(weixinDepositLog.getDepositMoney().intValue());
                //                String wxMchPay = cacheService.getBrandRemoteConfigValue(accountId, BrandConstant.WX_MCH_PAY_SWITCH);
                // 根据支付订单号判断订单支付的时候是否使用微信服务商支付
                RechargePayType one = rechargePayTypeDao.getOne(weixinDepositLog.getOut_trade_no());
                boolean isMchPay = false;
                // 非空且为微信服务商支付
                if (Objects.nonNull(one) && one.getType() == 1){
                    isMchPay = true;
                }
                isSucc = WeixinPay.returnMoney(weixinPayConfig, weixinDepositLog.getOut_trade_no(), weixinDepositLog.getOut_refund_no(), money, money, isMchPay);

                if (isSucc) {
                    dealRefundDeposit(refundNO,user,operatorId,operatorName,operatorPhone,accountId,weixinDepositLog,time);
                    // 退款调用成功进行主动查询退款订单状态
                    String payApiType = isMchPay ? PayApiTypeEnum.WECHAT_MCH_V3.getApiType() : PayApiTypeEnum.WECHAT_V2.getApiType();
                    weixinPayService.sendPayMsg(refundNO, RechargeConstant.PAY_REFUND, payApiType);
                }
            } else if (weixinDepositLog.getType().equals(RechargeConstant.RECHARGE_ZFB_APP)) {
                log.info("支付宝app退押金");
                /**获取平台支付宝支付信息*/ /**支付宝app*/
                ZfbPayConfig zfbPayConfig = zfbPayConfigService.getByAccountId(accountId, RechargeConstant.ZFB_PAY_APP);
                /**生成微信退款订单号*/
                weixinDepositLog.setOut_refund_no(refundNO);
                isSucc = ZFBReturn.returnMoney(zfbPayConfig, weixinDepositLog);
                if (isSucc) {
                    dealRefundDeposit(refundNO,user,operatorId,operatorName,operatorPhone,accountId,weixinDepositLog,time);
                }
            } else if (weixinDepositLog.getType().equals(RechargeConstant.RECHARGE_ZFB_XCX)) {
                log.info("支付宝小程序退押金");
                /**获取平台支付宝支付信息*/ /**支付宝小程序*/
                ZfbPayConfig zfbPayConfig = zfbPayConfigService.getByAccountId(accountId, RechargeConstant.ZFB_PAY_XCX);
                /**生成微信退款订单号*/
                weixinDepositLog.setOut_refund_no(refundNO);
                isSucc = ZFBReturn.returnMoney(zfbPayConfig, weixinDepositLog);
                if (isSucc) {
                    dealRefundDeposit(refundNO,user,operatorId,operatorName,operatorPhone,accountId,weixinDepositLog,time);
                }
            } else if (weixinDepositLog.getType().equals(RechargeConstant.RECHARGE_PAY_PAL)) {
                log.info("PayPal退押金");
                //paypal退款
                weixinDepositLog.setOut_refund_no(refundNO);
                String resMsg = payPalService.returnDeposit(user, weixinDepositLog);
                LogUtil.info("paymentId:" + weixinDepositLog.getTransaction_id() + ",orderNo:" + weixinDepositLog.getOut_trade_no() + ",押金退还结果：" + resMsg);
                if ("ok".equals(resMsg)) {
                    isSucc = true;
                    dealRefundDeposit(refundNO,user,operatorId,operatorName,operatorPhone,accountId,weixinDepositLog,time);
                }
            } else if (weixinDepositLog.getType().equals(RechargeConstant.RECHARGE_PAY_ADAPAY)
                    || weixinDepositLog
                    .getType().equals(RechargeConstant.RECHARGE_PAY_ADAPAY_ZFB)) {
                log.info("汇付退押金");
                isAdaPay = true;
                weixinDepositLog.setOut_refund_no(refundNO);
                AdaPayConfig adaPayConfig = cacheService.getAdaPayConfig(user.getAccountId(),
                        AdaPayConstant.PAY_CHANNEL_WXXCX);
                List<UserAdaPayLog> userAdaPayLogs = userAdaPayLogService.getByPaymentId(weixinDepositLog.getOut_trade_no());
                log.info("汇付分账对象为{}",JSON.toJSONString(userAdaPayLogs));
                try {
                    if (userAdaPayLogs.isEmpty()) {
                        log.info("调用支付撤销对象进行退押金");
                        isSucc = PaymentUtil
                                .createReverse(adaPayConfig, weixinDepositLog.getOut_trade_no(), weixinDepositLog.getDepositMoney(), weixinDepositLog.getOut_refund_no());
                    } else {
                        log.info("调用退款对象进行退押金");
                        String pamentId = weixinDepositLog.getOut_trade_no();
                        List<DivMembers> list = new ArrayList<>();
                        for (UserAdaPayLog userAdaPayLog : userAdaPayLogs) {
                            pamentId = userAdaPayLog.getConfirmId();
                            DivMembers divMembers = new DivMembers(userAdaPayLog.getUserNO(), String.format("%.2f", userAdaPayLog.getMoney().doubleValue()
                                    / 100), "N");
                            list.add(divMembers);
                        }
                        String members = JSON.toJSONString(list);
                        log.info("退款分账对象为{}",members);
                        Map<String, Object> payment = PaymentUtil.executeRefund(adaPayConfig, pamentId, weixinDepositLog.getDepositMoney(), weixinDepositLog.getOut_refund_no(), members);
                        if (payment.get("status").equals(AdaPayConstant.PAY_STATUS_PENDING) || payment.get("status").equals(
                                AdaPayConstant.PAY_STATUS_SUCCEEDED)) {
                            isSucc = true;
                        }
                    }
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }

            if (isSucc) {
                returnSuccNum++;
                if (isAdaPay){
                    RefundOrder refundOrder = new RefundOrder(weixinDepositLog.getOut_trade_no(),refundNO,weixinDepositLog.getDepositMoney(),weixinDepositLog.getDepositMoney(),
                            time,RefundConstant.REFUND_PENDING,false, weixinDepositLog.getOut_trade_no(),
                            null,null,null,false,null,"复用字段-执行退押金逻辑分支",null,null,null,
                            operatorId,operatorName,operatorPhone,null,null,null,null,null,
                            accountId,0d,0d,null,userId,null,null,null,0d,0d,
                            null,null,null,null);
                    refundOrderDao.insert(refundOrder);
                }
            } else {
                log.warn("押金退还失败，支付平台订单号=" + weixinDepositLog.getTransaction_id());
                if (isAdaPay) {
                    RefundOrder refundOrder = new RefundOrder(weixinDepositLog.getOut_trade_no(),refundNO,weixinDepositLog.getDepositMoney(),
                            weixinDepositLog.getDepositMoney(),time,RefundConstant.REFUND_FAIL,false,
                            weixinDepositLog.getOut_refund_no(), null,null,null,false,null,"复用字段-执行退押金逻辑分支",null,null,null,
                            operatorId,operatorName,operatorPhone,null,null,null,null,null,
                            accountId,0d,0d,null,userId,null,null,null,0d,0d,
                            null,null,null,null);
                    refundOrderDao.insert(refundOrder);
                }
            }
        }

        /**如果全部成功，更改押金状态*/
        if (returnSuccNum == weixinDepositLogs.size()) {
            userService.updateDeposit(userId, 0);
        } else {
            DepositApply depositApply = new DepositApply(user.getAccountId(),user.getUserId(),user.getPhone(),user.getDepositMoney().intValue(),
                    0,new Date(),RechargeConstant.PLATFORM_TYPE_WEIXIN);
            depositApplyService.add(depositApply);
            throw new BaseException("-3017", "申请成功,预计1-3个工作日原路退回支付账号，请您注意查收");
        }
    }

    private void dealRefundDeposit(String refundNO, User user, Integer operatorId, String operatorName, String operatorPhone, Integer accountId,  WeixinDepositLog weixinDepositLog, String time){
        // 执行退押金记录
//        WeixinDepositLog weixinDepositLog = weixinDepositLogService.getByOrderNo("rechargeNO");

        log.info("押金退还成功，支付平台订单号=" + weixinDepositLog.getTransaction_id());
        /**修改押金金额*/
        userService.updateDepositMoney(user.getUserId(), -weixinDepositLog.getDepositMoney());
//        returnSuccNum++;
        /**更新押金退还记录*/
        WeixinDepositLog weixinDepositLogUpdate = new WeixinDepositLog();
        weixinDepositLogUpdate.setReturnTime(time);
        weixinDepositLogUpdate.setTransaction_id(weixinDepositLog.getTransaction_id());
        weixinDepositLogUpdate.setOut_refund_no(weixinDepositLog.getOut_refund_no());
        weixinDepositLogService.updateReturn(weixinDepositLogUpdate);
        /**记录资金变动日志*/
        UserAccountLog userAccountLog = new UserAccountLog();
        userAccountLog.setMoneyType(0);
        userAccountLog.setAccountId(accountId);
        userAccountLog.setMoney(weixinDepositLog.getDepositMoney());
        userAccountLog.setUserId(user.getUserId());
        userAccountLog.setOperaTime(time);
        userAccountLog.setRemark("押金退还");
        userAccountLog.setType(0);
        userAccountLogService.insert(userAccountLog);
        String orderNo = weixinDepositLog.getOut_trade_no();
        if (weixinDepositLog.getType().equals(RechargeConstant.RECHARGE_PAY_ADAPAY)
                || weixinDepositLog.getType().equals(RechargeConstant.RECHARGE_PAY_ADAPAY_ZFB)) {
            AdaPayLog adaPayLog = adaPayLogDao.getByAdaPayId(weixinDepositLog.getOut_trade_no());
            orderNo = adaPayLog.getOrderNO();
        }
        Recharge recharge = rechargeService.getByOrderNO(orderNo);
        log.info("查询区域押金：userId=" + user.getUserId() + "accountId=" + recharge.getAdAccountId());
        UserAccountMoney depositMoney = userAccountMoneyService.getByAccountId(user.getUserId(), BalanceLogChangeTypeContent.capitalType_deposit, recharge.getAdAccountId());
        if (depositMoney != null) {
            depositMoney.setMoney(-depositMoney.getMoney());
            depositMoney.setUpdateTime(new DateTime(time).getTime());
            userAccountMoneyDao.edit(depositMoney);
        }
        List<String> merchantNOList = new ArrayList<>();
        merchantNOList.add(recharge.getOrderNO());
        Account account = accountService.getByAccountId(recharge.getAdAccountId());
        adaPayService.pushRefundDetailLog(user, account, weixinDepositLog.getDepositMoney(), refundNO, refundNO,
                recharge, operatorId, operatorName, operatorPhone, BusinessConstant.BUSINESS_USER_REFUND_DEPOSIT, null, null,new DateTime(time));
        adaPayService.pushRefundLog(user, account, weixinDepositLog.getDepositMoney(), refundNO, merchantNOList, recharge, RefundLogContent.deposit_Refund,
                null, operatorId, operatorName, operatorPhone, null,new DateTime(time));
        BalanceChange balanceChange = new BalanceChange(user.getUserId(), user.getPhone(), user.getName()
                , account.getAccountId(), user.getAccountId(), weixinDepositLog.getDepositMoney().longValue(), weixinDepositLog.getDepositMoney().longValue()
                , 0L, IncomeTypeContent.inComeRefund,
                BalanceLogChangeTypeContent.capitalType_deposit, BalanceLogCapitalTypeContent.USER_REFUNDS_DEPOSIT
                , new DateTime(time).getTime(), "退押金", refundNO);
        pushMsgLogService.sendPushLog(JSON.toJSONString(balanceChange), TableNameConstant.BALANCECHANGE);
    }

}  